package com.zx.mes.hyl.linked;

/**
 * <p>带有虚拟节点的链表</p>
 * @author huayunlong
 * @date 2018-8-3
 */
public class DummyLinkedList<E> {

    private class Node{

        public E e;
        public Node next;

        public Node(){
            this.e = null;
            this.next = null;
        }
        public Node(E e){
            this.e = e;
            this.next = null;
        }
        public Node(E e,Node next){
            this.e = e;
            this.next = next;
        }

        @Override
        public String toString() {
            return e.toString();
        }
    }

    private int size = 0;
    private Node dummyNode = new Node();

    public void add(int index,E e){
        if (index < 0 && index > size) {
            throw new IndexOutOfBoundsException("插入下标位置有问题!");
        }
        Node pre = dummyNode;
        Node current = pre.next;
        for (int i = 0; i <index ; i++) {
            pre = pre.next;
            current = pre.next;
        }
        pre.next = new Node(e, current);
        size++;
    }

    public void addFirst(E e){
        add(0, e);
    }

    public void addLast(E e) {
        add(size, e);
    }

    public Node remove(int index){
        if (index < 0 && index > size) {
            throw new IndexOutOfBoundsException("下标越界!");
        }
        Node pre = dummyNode;
        Node current = pre.next;
        for (int i = 0; i <index; i++) {
            pre = pre.next;
            current = pre.next;
        }
        pre.next = current.next;
        current.next = null;
        size--;
        return current;
    }

    @Override
    public String toString() {
        Node pre = dummyNode;
        StringBuilder sb = new StringBuilder();
        sb.append("链表:");
        for (int i = 0; i <size ; i++) {
            pre = pre.next;
            sb.append(pre);
            if (pre == null) {

            }else {
                sb.append("-->");
            }
        }
        sb.append("  size:" + size);
        return sb.toString();
    }
}
